package com.tianji.learning.utils;

import lombok.Data;

import java.time.Duration;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 19311
 * @CreateTime: 2025-03-25
 * @Description: 延迟任务
 * @Version: 1.0
 */
@Data
public class DelayTask<D> implements Delayed {

    private Long deadLineNanos; // 延时执行时间的纳秒值
    private D data; // 延时任务的数据

    public DelayTask(Duration duration, D data) {
        this.deadLineNanos = System.nanoTime() + duration.toNanos();
        this.data = data;
    }
    /**
     * 1、用来获取队列中每个任务距离当前时间还有多久被执行
     * @param unit the time unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(Math.max(deadLineNanos - System.nanoTime(), 0), TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        long diff = this.getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        if (diff > 0) {
            return 1;
        } else if (diff < 0) {
            return -1;
        } else {
            return 0;
        }
    }
}
